package android.slc.module.component.mock;

import android.slc.box.core.property.SimpleWrapObjectProperty;
import android.slc.box.core.property.WrapDataChangeListener;
import android.slc.rx.SimpleObserver;
import android.slc.rx.SlcRxJavaUtils;
import io.reactivex.rxjava3.core.Observable;

import java.util.concurrent.TimeUnit;

public class MockManager {
    private static class Holder {
        private static final MockManager instance = new MockManager();
    }

    public static MockManager getInstance() {
        return Holder.instance;
    }

    private boolean useMock = false;
    private int mockPeriod = 4000;

    //自动测试
    private final SimpleWrapObjectProperty<Void> autoTestProperty = new SimpleWrapObjectProperty<>();

    public void init(boolean userMock, int mockPeriod) {
        this.useMock = userMock;
        this.mockPeriod = mockPeriod;
        if (this.useMock) {
            Observable.interval(mockPeriod, mockPeriod, TimeUnit.MILLISECONDS)
                    .compose(SlcRxJavaUtils.applyOoAndroidSchedulers())
                    .subscribe(new SimpleObserver<Long>() {
                        @Override
                        public void onNext(Long aLong) {
                            super.onNext(aLong);
                            try {
                                autoTestProperty.notifyChange();
                            } catch (Exception e) {

                            }
                        }
                    });
        }
    }

    public boolean isUseMock() {
        return useMock;
    }

    public int getMockPeriod() {
        return mockPeriod;
    }

    /**
     * 注册监听
     *
     * @param dataChangeListener
     */
    public void registerMockHeartbeatListener(WrapDataChangeListener<Void> dataChangeListener) {
        autoTestProperty.addListener(dataChangeListener);
    }

    public void unRegisterMockHeartbeatListener(WrapDataChangeListener<Void> dataChangeListener) {
        autoTestProperty.removeListener(dataChangeListener);
    }
}
